package com.matrix.geo.playmysqlgeo.config;

import com.github.pagehelper.autoconfigure.PageHelperAutoConfiguration;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;

import java.util.Iterator;
import java.util.List;

@Configuration
@ConditionalOnBean({SqlSessionFactory.class})
@AutoConfigureAfter({PageHelperAutoConfiguration.class})
@Lazy(false)
public class DynamicTypeHandlerAutoConfiguration implements InitializingBean {

    private final List<SqlSessionFactory> sqlSessionFactoryList;

    @Autowired
    public DynamicTypeHandlerAutoConfiguration(List<SqlSessionFactory> sqlSessionFactoryList) {
        this.sqlSessionFactoryList = sqlSessionFactoryList;
    }

    @Override
    public void afterPropertiesSet() {
        DynamicTypeHandlerInterceptor interceptor = new DynamicTypeHandlerInterceptor();
        Iterator<SqlSessionFactory> var2 = this.sqlSessionFactoryList.iterator();
        while(var2.hasNext()) {
            SqlSessionFactory sqlSessionFactory = var2.next();
            org.apache.ibatis.session.Configuration configuration = sqlSessionFactory.getConfiguration();
            sqlSessionFactory.getConfiguration().getTypeHandlerRegistry();
            if (!this.containsInterceptor(configuration, interceptor)) {
                configuration.addInterceptor(interceptor);
            }
        }
    }

    private boolean containsInterceptor(org.apache.ibatis.session.Configuration configuration, Interceptor interceptor) {
        try {
            return configuration.getInterceptors().stream().anyMatch((config) -> interceptor.getClass().isAssignableFrom(config.getClass()));
        } catch (Exception var4) {
            return false;
        }
    }

}
